import Axios from 'axios'
import qs from 'qs'
import Const from './const'

const axios = Axios.create({
  baseURL: Const.NET.END_POINT_WEB,
  headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  withCredentials: true
})

function Api() {
  function transformObjectToUrlencodedData(obj) {
    let p = []
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        p.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
      }
    }
    return p.join('&')
  }

  function req(method, url, json) {
    return new Promise((resolve, reject) => {
      let r = ''
      if (method === 'GET') {
        r = axios.get(`${url}?${transformObjectToUrlencodedData(json)}`)
      } else if (method === 'POST') {
        r = axios.post(url, json ? qs.stringify(json) : null)
      } else if (method === 'PUT') {
        r = axios.put(url, json ? qs.stringify(json) : null)
      } else if (method === 'DELETE') {
        r = axios.delete(`${url}?${transformObjectToUrlencodedData(json)}`)
      }

      if (r) {
        r.then(
          response => {
            let body = response.data

            if (body.hasOwnProperty('code') && body.code === 0) {
              return resolve(body.data)
            }

            return reject(body)
          },
          error => {
            reject(error)
          }
        )
      }
    })
  }

  return {
    Home: {
      track: (params) => { return req('GET', '/home/track', params) },
      stat: (params) => { return req('GET', '/home/stat', params) },
    },
    Game: {
      list: (params) => { return req('GET', '/game/list', params) },
    },
    Ad: {
      list: (params) => { return req('GET', '/ad/list', params) },
    },
    Article: {
      info: (params) => { return req('GET', '/article/info', params) },
    },
    BlackAccount: {
      search: (params) => { return req('GET', '/black-account/search', params) },
    },
    CustomerService: {
      search: (params) => { return req('GET', '/customer-service/search', params) },
    },
    GameAccount: {
      topLevelList: (params) => { return req('GET', '/game-account/top-level-list', params) },
      topLevelDeal: (params) => { return req('GET', '/game-account/top-level-deal', params) },
      statDeal: (params) => { return req('GET', '/game-account/stat-deal', params) },
    }
  }
}

export default new Api()
